<?php
/**
 * 功能：
 * 说明：
 * 创建日期：
 * 更新日期：
 * 作者：Mirze
 * 补充说明： 
 * 
 */
class Adapter_Mysql
{
	protected $_bind_enabled = false;
	protected $_conn;
	protected $_dsn;

	/**
     * 用于描绘 true、false 和 null 的数据库值
     */
    protected $_true_value = 1;
    protected $_false_value = 0;
    protected $_null_value = 'NULL';

    //数据库接受的日期格式
    protected $_timestamp_format = 'Y-m-d H:i:s';

	//是否将查询语句保存到日志
    protected $_log_enabled = false;
    //最后一次数据库操作的错误信息
    protected $_last_err;


    function __construct($dsn, $id)
    {
        if (! is_array($dsn)) {
            //$dsn = F::parseDSN($dsn);
			exit('invalid dsn');
        }

		$this->_dsn = $dsn;
        
        $this->_schema = $dsn['database'];
    }

    function connect($pconnect = false, $force_new = false)
    {
        if (is_resource($this->_conn)) { return; }

		if (isset($this->_dsn['port']) && $this->_dsn['port'] != '') {
            $host = $this->_dsn['host'] . ':' . $this->_dsn['port'];
        } else {
            $host = $this->_dsn['host'];
        }

        if (! isset($this->_dsn['login'])) {
            $this->_dsn['login'] = '';
        }

        if (! isset($this->_dsn['password'])) {
            $this->_dsn['password'] = '';
        }

        if ($pconnect) {
            $this->_conn = mysql_pconnect($host, $this->_dsn['login'], $this->_dsn['password'], $force_new);
        } else {
            $this->_conn = mysql_connect($host, $this->_dsn['login'], $this->_dsn['password'], $force_new);
        }

		if (! is_resource($this->_conn)) {
            exit('CONNECT DATABASE', mysql_error(), mysql_errno());
        }

        if (! empty($this->_dsn['database'])) {
            $this->execute('USE ' . $this->qid($this->_dsn['database']));
        }

        if (isset($this->_dsn['charset']) && $this->_dsn['charset'] != '') {
            $charset = $this->_dsn['charset'];
            $this->execute("SET NAMES '" . $charset . "'");
        }
	}

	public function pconnect()
	{
		$this->connect(true);
	}

	function nconnect()
    {
        $this->connect(false, true);
    }

	function qstr($value)
    {
        if (is_array($value)) {
            foreach ($value as $offset => $v) {
                $value[$offset] = $this->qstr($v);
            }
            return $value;
        }
        if (is_int($value)) { return $value; }
        if (is_bool($value)) {
            return $value ? $this->_true_value : $this->_false_value;
        }
        if (is_null($value)) {
            return $this->_null_value;
        }
        if (! ($value instanceof QDB_Expr)) {
            return "'" . mysql_real_escape_string($value, $this->_conn) . "'";
        }
        return $value->formatToString($this);
    }

	protected function _fakebind($sql, $inputarr)
    {
        $arr = explode('?', $sql);
        $sql = array_shift($arr);
        foreach ($inputarr as $value) {
            if (isset($arr[0])) {
                $sql .= $this->qstr($value) . array_shift($arr);
            }
        }
        return $sql;
    }

	/**
	 * (功能描述) 执行一个查询，返回一个查询对象或者 boolean 值，出错时抛出异常
	 *
	 * @param 
	 * @return
	 */
	function execute($sql, $inputarr = null)
    {
        if (is_array($inputarr)) {
            $sql = $this->_fakebind($sql, $inputarr);
        }

        if ($this->_log_enabled) {
            FLog::log('[DB EXECUTE] ' . str_replace("\n", ' ', $sql), FLog::DEBUG);
        }

        if (! $this->_conn) {
            $this->connect();
        }
        $result = mysql_query($sql, $this->_conn);

        if (is_resource($result)) {
            //return new QDB_Result_Mysql($result, $this->_fetch_mode);
			return $result;
        } elseif ($result) {
            $this->_last_err = null;
            $this->_last_err_code = null;
            return $result;
        } else {
            $this->_last_err = mysql_error($this->_conn);
            $this->_last_err_code = mysql_errno($this->_conn);
            $this->_has_failed_query = true;

            if ($this->_last_err_code == 1062) {
                //throw new QDB_Exception_DuplicateKey($sql, $this->_last_err, $this->_last_err_code);
            } else {
                //throw new QDB_Exception($sql, $this->_last_err, $this->_last_err_code);
            }
			exit($this->_last_err);
        }
    }

	/**
	 * (功能描述)
	 *
	 * @param 
	 * @return
	 */
	public function insert()
	{
		
	}

	/**
	 * (功能描述)
	 *
	 * @param 
	 * @return
	 */
	public function update()
	{
		
	}

	/**
	 * (功能描述)
	 *
	 * @param 
	 * @return
	 */
	public function delete()
	{
		
	}


	/**
	 * (功能描述) 进行限定范围的查询
	 *
	 * @param 
	 * @return
	 */
	function selectLimit($sql, $offset = 0, $length = 30, array $inputarr = null)
    {
        if (! is_null($offset)) {
            $sql .= ' LIMIT ' . (int) $offset;
            if (! is_null($length)) {
                $sql .= ', ' . (int) $length;
            } else {
                $sql .= ', 18446744073709551615';
            }
        } elseif (! is_null($length)) {
            $sql .= ' LIMIT ' . (int) $length;
        }
        return $this->execute($sql, $inputarr);
    }

	//获取自增字段的最后一个值或者 nextID() 方法产生的最后一个值
	function insertID()
    {
        return mysql_insert_id($this->_conn);
    }

	//返回最近一次数据库操作受到影响的记录数
    function affectedRows()
    {
        return mysql_affected_rows($this->_conn);
    }




}